package com.test.fundible.fundible_04_home;

import static com.test.fundible.fundible_00_utils.FundibleConfigs.PermissionCode_Home;
import static com.test.fundible.fundible_00_utils.FundibleUtil.startLoading;
import static com.test.fundible.fundible_00_utils.FundibleUtil.stopLoading;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.test.fundible.fundible_00_analytics.FundibleUtil.FundibleAnalyticsUtil;
import com.test.fundible.R;
import com.test.fundible.fundible_06_loan_apply.LoanApplyActivity;
import com.test.fundible.fundible_05_process.Pro_fundiblecessAct_fundibleivity;
import com.test.fundible.fundible_06_loan_apply.LoanApplyActivity_OldUser;
import com.test.fundible.fundible_07_loan_status.Base_fundibleLnFragment;
import com.test.fundible.fundible_01_launcher.App_fundibleShow_fundibleCustomize;
import com.test.fundible.fundible_05_process.Pro_fundiblecessIn_fundiblefo;
import com.test.fundible.fundible_00_http.OkHttpUtil;
import com.test.fundible.fundible_00_utils.FundibleUtil;

import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class HomeFr_fundibleagment extends Base_fundibleLnFragment{

    private SwipeRefreshLayout refreshLayout;
    private TextView amountTv;
    private View applyBtn;
    private TextView viewProcessTv;

    private Runnable processR_fundibleunnable;

    private final Runnable applyRunn_fundibleable = () -> {

        OkHttpUtil.getInstance_fundible().uploadEventPoint("HOME","APPLY_CLICK","");

        String[] homePermissions = App_fundibleShow_fundibleCustomize.getInstance_fundible().getHomePermission_fundible();

        if (FundibleUtil.checkPermissions_fundible(requireActivity(), homePermissions)) {
            //device info upload
            try {
                if (FundibleUtil.didLogin_fundible()) {
                    FundibleAnalyticsUtil.INSTANCE.saveDeviceS2SInfo_fundible();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            //申请流程
            processR_fundibleunnable = () -> {
                //无流程：跳转到申请页
                if (Pro_fundiblecessIn_fundiblefo.getInstance_fundible().getSteps_fundible().isEmpty())
                    toApply();
                //有流程：跳转到流程页
                else startActivity(new Intent(requireContext(), Pro_fundiblecessAct_fundibleivity.class));
            };

            startLoading(requireContext(),"");
            OkHttpUtil.getInstance_fundible().requestUsPrcs(this::onUserProcessRe_fundiblesponse);

        } else
            EasyPermissions.requestPermissions(requireActivity(), getString(R.string.launch_permissions_all_fundible), PermissionCode_Home, homePermissions);

    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_fundible_home, container, false);

        refreshLayout = view.findViewById(R.id.ffh_refreshlayout);
        amountTv = view.findViewById(R.id.ffh_tv_amount);
        applyBtn = view.findViewById(R.id.ffh_btn_apply);
        viewProcessTv = view.findViewById(R.id.ffh_tv_view_process);

        refreshLayout.setOnRefreshListener(() -> {
            OkHttpUtil.getInstance_fundible().uploadEventPoint("HOME","REFRESH_CLICK","");
            refreshLayout.setRefreshing(false);
            startLoading(requireContext(),"");
            OkHttpUtil.getInstance_fundible().requestUsPrcs(this::onUserProcessRe_fundiblesponse);
        });

        initVie_fundiblew();

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        OkHttpUtil.getInstance_fundible().uploadEventPoint("HOME","START","");
        startLoading(requireContext(),"");
        OkHttpUtil.getInstance_fundible().requestHomeAmountList(this::initM_fundiblesg);
    }

    @Override
    public void onPause() {
        super.onPause();
        OkHttpUtil.getInstance_fundible().uploadEventPoint("HOME","END","");
    }


    @SuppressLint("SetTextI18n")
    private void initM_fundiblesg(){
        stopLoading();
        amountTv.setText(LnLi_fundiblemitInfo.getInstance_fundible().getLimitAmount_fundible()+" "+ LnLi_fundiblemitInfo.getInstance_fundible().getCurrency_fundible());
    }

    private void initVie_fundiblew(){

        //申请
        applyBtn.setOnClickListener(v -> applyRunn_fundibleable.run());

        viewProcessTv.setOnClickListener(v -> {
            processR_fundibleunnable = () -> new Proce_fundiblessDialog(requireContext(),"HOME", applyRunn_fundibleable).show();
            FundibleUtil.startLoading(requireContext(),"");
            OkHttpUtil.getInstance_fundible().requestUsPrcs(this::onUserProcessRe_fundiblesponse);
        });

    }

    public void onUserProcessRe_fundiblesponse(){
        String state = Pro_fundiblecessIn_fundiblefo.getInstance_fundible().getFundibleUtil();
        if (FundibleUtil.isStateChange_fundible(state)) {//刷新用户状态
            stopLoading();
            FragmentActivity activity = requireActivity();
            FundibleUtil.clearState_fundible();
            activity.startActivity(new Intent(activity, MainAct_fundibleivity.class));
            activity.finish();
        }else if (processR_fundibleunnable !=null) {
            stopLoading();
            processR_fundibleunnable.run();
            processR_fundibleunnable = null;
        }else OkHttpUtil.getInstance_fundible().requestHomeAmountList(this::initM_fundiblesg);
    }


    public void onPermissionsGranted() {
        applyRunn_fundibleable.run();
    }

    //跳转到申请页
    private void toApply(){
        if (Pro_fundiblecessIn_fundiblefo.getInstance_fundible().isNewUser_fundible())
            startActivity(new Intent(requireActivity(), LoanApplyActivity.class));
        else startActivity(new Intent(requireActivity(), LoanApplyActivity_OldUser.class));
    }

}